<?php

namespace app\api\model\service;

use app\api\model\service\MoneyLog;
use app\api\model\service\ScoreLog;
use think\Db;
use think\Model;
use think\Exception;
class User extends Model
{
    // 表名
    protected $name = 'user';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    public static function getMoney($uid)
    {
        return self::where(['id'=>$uid])->value('money');
    }

    public static function getTotalUser()
    {
        $daytime = strtotime(date("Y-m-d",time()));
        $start= $daytime-86400*6;
        $end = $daytime;
        $userTotal = [];
        $total = ceil(($end-$start)/86400);;
        for($a = 0;$a <=$total; $a++){
            $where['createtime'] = ['between',[86400*$a+$start,86400*$a+$start+86399]];
            $where['status'] = ['>',5];
            $userTotal[] = self::where($where)->count();
        }

        return $userTotal;
    }


    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

}
